/*
 * 作者: 侯晓宇
 * 时间: 2017-02-17
 * 说明：
 * Copyright (c) 2016-2017 中研沃兮
 */
define(function(require) {
	require("jquery");
	var c = require('app/utils/CommonUtils');
	var hc = require('app/utils/HttpClientUtils');
	var EchoLazyUtils = require('app/utils/EchoLazyUtils');
	var MsgInfoUtils = require('app/utils/MsgInfoUtils');
	var UserInfoUtils = require('app/utils/UserInfoUtils');
	var QQEmotionUtils = require('app/utils/QQEmotionUtils');
	var TimerUtils = require('app/utils/TimerUtils');
	var CacheUtils = require('app/utils/CacheUtils');
	var AudioPlayingUtils = require('app/utils/AudioPlayingUtils');
	var PhotoBrowserUtils = require('app/utils/PhotoBrowserUtils');
	var EventUtils = require('app/utils/EventUtils');
	
	var last_time = 0;
	var win = window;
	var action = {};
	EchoLazyUtils.load();
	
	
	function getchatstatus(type) {
		
	    var statustype = "";//非自己发送的信息         
		
		if(!c.isNull(type)){
			if (type == 0) { // loading...
				statustype = '<img src="../image/loading_more.gif" style="width: 40%;margin: auto;display: inline;">';
			}else if (type == 1) { // danger
				statustype = '<i class="aui-iconfont aui-icon-info aui-text-danger"></i>';
			}else if (type == 2) { // success
				statustype = '<i class="takeback aui-iconfont aui-text-warning">撤回</i>';
			}		
		}else{
			type = 3;	
		}
		
		var statusdiv =		
			statustype +
			'<input class="status_type" type="hidden" value="'+type+'">'
	    return statusdiv;
	}

	function setMsgloadingTimer(msgid){
		
		setTimeout(function(){
			var type = $("#"+msgid).find('.status_type').val() +"";
			
			if(type == "0"){
				var temp = getchatstatus(1);
				$("#"+msgid).find('.aui-chat-status').html(temp);
			}
		
		},30*1000);//15s
	}

	var registerTakeback = function(msgid){
		var item = $("#"+msgid).find(".takeback");
		item.click(function(){
			api.confirm({
				title: "温馨提示",
				msg: '是否选择撤回？',
	    		buttons: ['取消', '确定']
	        },function(ret,err){
	        	if(ret.buttonIndex == 2){ //确定
	        		var data = MsgInfoUtils.buildSendMsg({});
	        		data.msgid = msgid;
	        		data.type = "takeback";
	        		EventUtils.send(api.winName, 'send_room_msg', data);
	        	}
	        });
		});
	}

	var registerImgdisplay = function(msgid){
	
		var local_path = $("#img_"+msgid).data("local");
		var newsrc_path = $("#img_"+msgid).data("newsrc");
		var path = "";
		
		if(c.isNullStr(local_path)){
			path = newsrc_path;
		}else{
			path = local_path;
		}
			
		$("#img_"+msgid).click(function(e){
			PhotoBrowserUtils.open(path);
		});
		
	}

	function registerAudioplay(msgid){
		$("#audio_"+msgid).click(function(){ // start to play
			var msgid = $(this).data("msgid");
			var currentplay = AudioPlayingUtils.getCurrentplay_msgid();
			c.debug("registerAudioplay-currentplay:",currentplay);
			c.debug("registerAudioplay-msgid:",msgid);
			if(currentplay == null){
				AudioPlayingUtils._displayplaying(msgid);

			}else if(currentplay == msgid){
			
				AudioPlayingUtils._stopplaying(msgid);
			}else if(currentplay != msgid){
				
				AudioPlayingUtils._stopallplaying();
				setTimeout(function(){
					AudioPlayingUtils._displayplaying(msgid);
				},500);
				
			}
			
		});
	}

	function getheadimgurl_div(headimgurl) {
		var cacheheadimgurl = null;
		var imgdiv = null;
		if (c.isNullStr(headimgurl)) {
			headimgurl = "../image/user_avatar_default.jpg";
			imgdiv = '<img src="' + headimgurl + '" >';
		} else {
			headimgurl = c.handleUrl(headimgurl);
			//网络地址，缓存图片
			cacheheadimgurl = CacheUtils.imageCache(headimgurl);

			if (headimgurl == cacheheadimgurl) { //第一次访问远程图片，还未进行缓存
				imgdiv = '<img data-echo="' + headimgurl + '" src="../image/user_avatar_default.jpg">';
			} else { //数据库中已经存储缓存记录
				imgdiv = '<img src="' + cacheheadimgurl + '">';
			}
		}
		return imgdiv;
	}

	function renderTimeDiv(time){
		var timediv = $('<div class="aui-chat-header">'+c.timeFormat(time)+'</div>');
		return timediv;
	}

	function removeMsgItem(o){
		var msgid = o.msgid
		$("#"+msgid).hide();
	}

	function renderMsgItem(o, send, history) {
		
		c.debug("msg-item",o);
		
		if (c.isNull(send)) {
			send = false;
		}
		if (c.isNull(history)) {
			history = false;
		}
		var content_div = "";
		if (o.type == "txt") {
			content_div =
				'<div class="aui-chat-content" data-msgid="' + o.msgid + '">' +
				'<div class="aui-chat-arrow"></div>' +
				QQEmotionUtils.transText(o.content) +
				'</div>';

		}else if(o.type == "audio"){
		
			var audio_w = parseInt( parseInt(o.sec)/60 * 65) + 35;
			content_div = 
	        '<div class="aui-chat-content" data-msgid="'+o.msgid+'" style="min-width:2rem; width:'+audio_w+'%;" data-local="'+o.content+'" data-newsrc="'+c.handleUrl(o.newsrc)+'" tapmode id="audio_'+o.msgid+'">'+
	            '<div class="aui-chat-arrow"></div>'+
	            '<div class="unread" id="unread_'+o.msgid+'" style=""></div>'+
	            '<div style="position: absolute;right: 0;bottom: 0;font-size: 0.6rem;margin-right: -1rem;">'+o.sec+'s</div>'+
	            '<div style="position: absolute;right: 0;bottom: 0;font-size: 0.6rem;margin-right: 0.2rem;">转至第'+(parseInt(o.ppt)+1)+'页</div>'+
	            '<span id="audioplay_'+o.msgid+'" data-num="'+(parseInt(o.ppt))+'" data-playing="0" class="msg-icon-mic-l3 msg-icon-play" style="">&nbsp;&nbsp;&nbsp;&nbsp;</span>'+
	        '</div>';
		}else if(o.type == "img"){
			
			//
			
			var imgdiv = "";
			if(send){
				imgdiv = '<img src="'+o.content+'"/>';
			}else{
				imgdiv = '<img src="../image/picture_loading.png" data-echo="'+o.newsrc+'" />';
			}
			content_div = 
	      '<div class="aui-chat-content" data-msgid="'+o.msgid+'" data-newsrc="'+o.newsrc+'" data-local="'+o.content+'" tapmode id="img_'+o.msgid+'">'+
	          '<div class="aui-chat-arrow"></div>'+
	          imgdiv+ 
	      '</div>';
		}
//		else if(o.type == "like"){
//			return;
//		}

		var status_div = "";

		var myself_class = "";
		var myself_span = "";
		
		if (send) {
			myself_class = "myself";
			myself_span = '<span class="aui-label aui-label-warning">自己</span>'

			//补全头像和姓名等信息
			o = MsgInfoUtils.fillInfo(o);
			status_div = getchatstatus(0);
			
		}else{
			if(o.useruuid == UserInfoUtils.getLoginedUser().userid){
				myself_class = "myself";
				myself_span = '<span class="aui-label aui-label-warning">自己</span>'
				status_div = getchatstatus(2);
			}else{
				status_div = getchatstatus();
			}
			
		}
		
		var item = $(
		
			'<div class="aui-chat-item aui-chat-left ' + myself_class + '" id="' + o.msgid + '">' +
	            '<div class="aui-chat-media">'+
	                getheadimgurl_div(o.headimgurl) +
	            '</div>'+
	            '<div class="aui-chat-inner">'+
	                '<div class="aui-chat-name">' + o.name + myself_span + '</div>' +
	                content_div +
	                '<div class="aui-chat-status aui-chat-status-refresh" style="padding-left:0.5rem;">'+
						status_div+
	                '</div>'+
	            '</div>'+
	        '</div>'
		);

		if (history) {
			if(last_time != 0){
				if(Math.abs(o.time - last_time)>1000*60*5){ //大于5分钟的
					$("#msg-list").prepend(renderTimeDiv(o.time));
				}
			}
			
			$("#msg-list").prepend(item);
						
		} else {
		
			if(Math.abs(o.time - last_time)>1000*60*5){ //大于5分钟的
				$("#clearfix").before(renderTimeDiv(o.time));
			}
			$("#clearfix").before(item);
		}
		
		
		
		if(send){
			//设置计时器 状态发送计时器
			setMsgloadingTimer(o.msgid);
		}
		
		//记录item的时间
		last_time = o.time;
		EchoLazyUtils.load();
		
		//注册语音监听和图片监听
		if(o.type == "audio"){
			registerAudioplay(o.msgid);
		}else if(o.type == "img"){
			registerImgdisplay(o.msgid);
		}
		
	}

	action.renderRecieveHistory = function(data){
		renderMsgItem(data,false,true);
		registerTakeback(data.msgid);
	}
	action.renderRecieveMsg = function(data) {
		
		if(data.type == "txt" || data.type =="audio" || data.type == "img"){
			
			if(data.sessionid == UserInfoUtils.getCurrentRoomSessionid() 
				&&
				data.useruuid == UserInfoUtils.getLoginedUser().userid){
			//自己接收到服务器确认信息
				$("#"+data.msgid).find(".aui-chat-status").html(getchatstatus(2));
				registerTakeback(data.msgid);
			}else{
			//其他人发送到
				renderMsgItem(data);
			}
			
		}else if(data.type == "takeback"){
			removeMsgItem(data);
		}
		
	}
	action.renderSendMsg = function(data) {
	
		if(data.type == "ignore" || data.type == "takeback"){
			return;
		}
		var send = true;
		var history = false;
		renderMsgItem(data, self, history);
		
		//Scroll to Bottom
		document.body.scrollTop = $("#msg-list")[0].scrollHeight;
	}

	return action;
});